# -*- encoding: utf-8 -*-

"""
@File:      tc_libfastjson_libfastjson_func_003.py
@Time:      2024/04/01 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_libfastjson_libfastjson_func_003.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """

    PARAM_DIC = {"pkg_name": "libfastjson libfastjson-devel gcc valgrind"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = '''cat >fjson_test3.c<<"EOF"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libfastjson/json.h>

int main() {
    // 创建一个 JSON 对象
    fjson_object *json_obj = fjson_object_new_object();

    // 添加一个字符串键值对至 JSON 对象
    fjson_object_object_add(json_obj, "name", fjson_object_new_string("John Doe"));

    // 添加一个整数键值对至 JSON 对象
    fjson_object_object_add(json_obj, "age", fjson_object_new_int(30));

    // 将 JSON 对象转换为字符串并打印
    const char *json_str = fjson_object_to_json_string(json_obj);
    printf("%s\\n", json_str);

    // 释放 JSON 对象的内存
    fjson_object_put(json_obj);

    // 故意缺失释放内存的步骤，用于测试 Valgrind 检测内存泄漏
    char *leak_test = malloc(10); // 分配内存
    if (leak_test != NULL) {
        strcpy(leak_test, "leak"); // 复制字符串到分配的内存，注意避免溢出
    }
    // 注意：这里故意没有释放 leak_test 内存

    return 0; // 程序退出前，没有释放 leak_test
}
EOF'''
        self.cmd(cmdline)


    def test(self):
        self.cmd("gcc -o fjson_test3 fjson_test3.c -lfastjson")
        self.cmd("valgrind --leak-check=full ./fjson_test3 > fjson.log 2>&1")
        code, fjson_result = self.cmd("cat fjson.log", ignore_status=True)
        self.assertIn("10 bytes in 1 blocks are definitely lost in loss record 1 of 1", fjson_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf fjson_test3.c fjson_test3 fjson.log")
